package com.crawler.gmail.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crawler.gmail.enums.MailProtocolEnum;
import com.crawler.gmail.utils.TimeStampUtil;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 通过接口和招聘工程通讯
 * <详细介绍>
 *
 * @author 王明明
 * @since wiki
 */
public class RecruitmentHttpTools {
    private final static Logger LOGGER = LoggerFactory.getLogger(RecruitmentHttpTools.class);
    private final static String ENV = System.getProperty("env");

        public static final String HOST = ENV.equals("env") ? "http://s.xinrenxinshi.com/recruitment/service"
                :"http://s114.devtest.vip:8886/recruitment/service";
//    public static final String HOST = "http://s114.devtest.vip:8886/recruitment/service";

    // 获取所有的邮箱配置
    public static List<EmailFetchSettingDO> getAllEmailSetting() {
        String path = "/ajax-get-gmail";
        List<EmailFetchSettingDO> emailFetchSettingDOList = new ArrayList<>();
        try {
            String res = doGet(path);
//
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.getIntValue("code") == 0) {
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject tmp = jsonArray.getJSONObject(i);
                    EmailFetchSettingDO emailFetchSettingDO = new EmailFetchSettingDO();
                    emailFetchSettingDO.setUsername(tmp.getString("email"));
                    emailFetchSettingDO.setPassword(tmp.getString("password"));
                    emailFetchSettingDO.setProtocol(MailProtocolEnum.findByDesc(tmp.getString("protocol").toLowerCase()).getValue());
                    emailFetchSettingDO.setPort(tmp.getInteger("port"));
                    emailFetchSettingDO.setHost(tmp.getString("hostname"));

                    emailFetchSettingDO.setSsl(tmp.getBoolean("ssl"));
                    if (tmp.getInteger("port").equals(993) || tmp.getInteger("port").equals(995)){
                        emailFetchSettingDO.setSsl(true);
                    }
                    Long fetchDate = tmp.getLong("lastFetchDate") > tmp.getLong("fetchDate") ? tmp.getLong("lastFetchDate") : tmp.getLong("fetchDate");
                    JSONArray channels = tmp.getJSONArray("channel");
                    List<ChannelTO> channelTOList = new ArrayList<>();
                    if (channels.size() != 0){
                        for (int j = 0; j < channels.size(); j++) {
                            JSONObject channelObj = channels.getJSONObject(j);

                            ChannelTO channelTO = channelObj.toJavaObject(ChannelTO.class);
//                            channelTO.setChannelType(channelObj.getInteger("id"));
//                            channelTO.setKeyWords(channelObj.getString("keyWords"));
//                            channelTO.setOutBoxs(channelObj.getString("outBoxs"));
                            channelTOList.add(channelTO);
                        }
                    }
                    emailFetchSettingDO.setChannel(channelTOList);
                    emailFetchSettingDO.setLastFetchTime(TimeStampUtil.LongTo13(fetchDate));
                    emailFetchSettingDO.setSettingId(tmp.getString("settingId"));
                    emailFetchSettingDOList.add(emailFetchSettingDO);
                }

            } else {
                LOGGER.error("邮箱获取接口不成功 {}", res);
            }
        } catch (Exception e) {
            LOGGER.error("ajax-get-gmail error ", e);
        }
        return emailFetchSettingDOList;
    }

    // 更新邮箱最后抓取时间
    public static void updateEmailFetchTime(String settingId, Long lastFetchDate) {
        String path = "/ajax-set-gmail-lastFetchDate";
        path = path + "?settingId=" + settingId + "&lastFetchDate=" + TimeStampUtil.LongTo10(lastFetchDate);
        try {
            String res = doGet(path);
            LOGGER.info("updateEmailFetchTime {}", res);
        } catch (IOException e) {
            LOGGER.info("更新邮箱有效性信息出错", e);

        }
    }

    // 更新邮箱有效性信息
    public static void updateEmailValid(EmailFetchSettingDO settingDO, Integer valid) {
        LOGGER.info("开始更新邮箱有效性 {} {}", settingDO.getUsername(), valid);
        String path = "/ajax-set-gmail-valid";
        path = path + "?settingId=" + settingDO.getSettingId() + "&valid=" + valid;
        try {
            String res = doGet(path);
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.getIntValue("code") == 0) {
                LOGGER.info("更新邮箱有效性信息成功 {} ", settingDO.getUsername());
            } else {
                LOGGER.info("更新邮箱有效性信息失败 {}", res);
            }
        } catch (IOException e) {
            LOGGER.info("更新邮箱有效性信息出错", e);

        }
    }

    // 回传邮件基础信息
    public static void saveMailInfo(String email, String addresser, long sendTime, String fileKey,
                                    String subject, String attachment, Integer channelType, long lastDate) {
        String path = "/ajax-post-back-resume";
        email = URLEncoder.encode(email);
        addresser = URLEncoder.encode(addresser);
        fileKey = URLEncoder.encode(fileKey);
        subject = URLEncoder.encode(subject);
        attachment = URLEncoder.encode(attachment);
        String query = "email=" + email + "&addresser=" + addresser + "&sendTime=" + sendTime;
        query = query + "&fileKey=" + fileKey + "&subject=" + subject + "&attachment=" + attachment + "&channelType=" + channelType + "&lastDate=" + lastDate;
        path = path + "?" + query;
        try {
            String res = doGet(path);
            LOGGER.info("邮件保存成功 {}", res);
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info("邮件保存失败", e);

        }
    }

    //发送请求
    public static String doPost(String path) {
        String uri = HOST + path;

        return null;
    }

    public static String doGet(String path) throws IOException {
        String uri = HOST + path;
        LOGGER.info("GET -> {}", uri);

        return Jsoup.connect(uri).ignoreHttpErrors(true).ignoreContentType(true).get().text();
    }

    public static void main(String[] args) {
        getAllEmailSetting();
    }
}
